package com.yilin.medical.activity;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;

import android.widget.RelativeLayout;
import android.widget.LinearLayout.LayoutParams;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yilin.medical.R;
import com.yilin.medical.adapter.GridAdapter;
import com.yilin.medical.http.AsyTask;
import com.yilin.medical.lsh.Banner;
import com.yilin.medical.lsh.BaseResult;
import com.yilin.medical.lsh.Http;
import com.yilin.medical.utils.PromptManager;

/**
 * 首页
 * 
 * @author lijianqun
 * 
 */
public class HomeActivity extends BaseActivity implements OnItemClickListener {
	private com.yilin.medical.views.MesureGridView mGridViewHome;
	private Context context;
	int[] homeItemIds = { R.drawable.kecheng_home, R.drawable.huizhen_home,
			R.drawable.huiyi_home, R.drawable.zhinan_home };


	private ViewPager pager;
	private List<View> data;

	private DisplayImageOptions options;
	private LinearLayout statusbar;

	public static final String TYPE_COURSE = "course";
	public static final String TYPE_CONSULATION = "consultation";
	public static final String TYPE_MEETING = "meeting";
	public static final String TYPE_GUIDE = "guide";
	public static final String TYPE_KEY ="HomeActivity";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentViewWithTitle(R.layout.activity_home);
		mTitle.getTitle().setText("主界面");
		mTitle.setImageView(R.drawable.person_light, View.VISIBLE, this);
		context = this;
		initView();
		initData();
		registerListener();
	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		Intent intent;
		switch (v.getId()) {
		case R.id.title_iv:
			intent = new Intent(context, PersonalCenterActivity.class);
			startActivity(intent);
		}
	}

	@SuppressWarnings("unchecked")
	private void initData() {
		Type type = new TypeToken<BaseResult<Map<String, Banner>>>() {
		}.getType();
		new AsyTask<BaseResult<Map<String, Banner>>>(HomeActivity.this,
				Http.HttpApis.banner, type, true) {

			@Override
			protected void onPost(BaseResult<Map<String, Banner>> result) {
				// TODO Auto-generated method stub
				removeProgressDialog();
				if (result.getSimpleException() != null) {
					PromptManager.showToast(HomeActivity.this, result
							.getSimpleException().getMessage());
				} else {
					// 初始化
					initImage(result.getData());
				}
			}
		}.execute(new HashMap<String, Object>());
	}

	private void initImage(final Map<String, Banner> source) {
		data = new ArrayList<View>();
		PagerAdapter pagerAdapter = new PagerAdapter() {

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return source.size();
			}

			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object) {
				// TODO Auto-generated method stub
				container.removeView(data.get(position));
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				// TODO Auto-generated method stub
				container.addView(data.get(position));
				return data.get(position);
			}
		};

		// Set<Entry<String, Banner>> entrySet = source.entrySet();
		// source.
		for (int i = 0; i < source.size(); i++) {
			Banner ban = source.get(String.valueOf(i));
			ImageView iv = new ImageView(this);
			RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,
					android.widget.RelativeLayout.LayoutParams.MATCH_PARENT);
			iv.setLayoutParams(param);
			ImageLoader.getInstance()
					.displayImage(ban.getPicUrl(), iv, options);
			iv.setScaleType(ScaleType.FIT_XY);

			data.add(iv);
			View mView = new View(this);
			mView.setBackgroundResource(R.drawable.selector);

			LayoutParams params = new LayoutParams(10, 10);
			params.gravity = Gravity.CENTER_VERTICAL;
			params.leftMargin = 20;
			mView.setLayoutParams(params);
			mView.setEnabled(false);
			statusbar.addView(mView);
		}
		statusbar.getChildAt(0).setEnabled(true);
		pager.setAdapter(pagerAdapter);
		pagerAdapter.notifyDataSetChanged();

	}

	private void initView() {
		statusbar = (LinearLayout) findViewById(R.id.homepage_adv_linearlayout);
		pager = (ViewPager) findViewById(R.id.viewpage);
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_launcher) // 设置图片在下载期间显示的图片
				.showImageForEmptyUri(R.drawable.ic_launcher)// 设置图片Uri为空或是错误的时候显示的图片
				.showImageOnFail(R.drawable.ic_launcher) // 设置图片加载/解码过程中错误时候显示的图片
				.cacheInMemory(true)// 设置下载的图片是否缓存在内存中
				.cacheOnDisc(true)// 设置下载的图片是否缓存在SD卡中
				.build();// 构建完成
		pager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				if (statusbar == null)
					return;
				View view = statusbar.getChildAt((position - 1)
						% pager.getAdapter().getCount());
				if (view != null) {
					view.setEnabled(false);
				}

				view = statusbar.getChildAt((position + 1)
						% pager.getAdapter().getCount());
				if (view != null) {
					view.setEnabled(false);
				}

				// 把当前圆球置为选中状态
				statusbar.getChildAt(position).setEnabled(true);
				pager.setCurrentItem(position, false);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});

		mGridViewHome = (com.yilin.medical.views.MesureGridView) findViewById(R.id.gv_home);
		mGridViewHome.setAdapter(new GridAdapter(context, homeItemIds));

	}

	private void registerListener() {
		mGridViewHome.setOnItemClickListener(this);

	}

	/**
	 * gridview的点击首页其他入口切换
	 */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		Intent intent;
		switch (position) {
		case 0:
			// 课程
			intent = new Intent(context, KeChengHomeActivity.class);
			intent.putExtra(TYPE_KEY, TYPE_COURSE);
			startActivity(intent);
			break;
		case 1:
			// 会诊
			intent = new Intent(context, HuiZhenHomeActivity.class);
			startActivity(intent);
			break;
		case 2:
			// 会议
			intent = new Intent(context, KeChengHomeActivity.class);
			intent.putExtra(TYPE_KEY, TYPE_MEETING);
			startActivity(intent);
			break;
		case 3:
			// 指南
			intent = new Intent(context, KeChengHomeActivity.class);
			intent.putExtra(TYPE_KEY, TYPE_GUIDE);
			startActivity(intent);
			break;
		}
	}

}